from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
from email.header import Header

from django.conf import settings


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def gen_vcode_msg(vcode, from_addr, to_addr, text):
    # 构建一个文本的mail对象
    text = text
    msg = MIMEText(text.format(vcode),
                   'plain', 'utf-8')
    msg['From'] = _format_addr('张大帅旅游网<%s>' % from_addr)
    msg['To'] = _format_addr('用户<%s>' % to_addr)
    msg['Subject'] = Header('张大帅旅游网，回复信息', 'utf-8').encode()
    return msg


def send_vcode(to_addr, smtp_server, from_addr, password, send_me):
    # 构建一个 smtp 对象
    server = smtplib.SMTP(smtp_server, 25)
    # 设置一个调试级别
    server.set_debuglevel(1)
    # 登录
    server.login(from_addr, password)
    # 发送邮件
    vcode = '谢谢'
    msg = gen_vcode_msg(vcode, from_addr, to_addr, send_me)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
    return vcode


if __name__ == '__main__':
    from_addr = '3376184110@qq.com'
    to_addr = '3376184110@qq.com'
    password = 'keowkcugndggdbjb'
    smtp_server = 'smtp.qq.com'
    code = send_vcode(smtp_server, from_addr, password, to_addr)
    print('发送的验证码：', code)
